# coding=utf-8

import web
from web.utils import storage

from db import connection

db = connection.default

def get_all_partner_names(insert_empty = True):
    """
    获取所有合作商家的名字及内码列表
    """
    sets = db.select('partner', order = 'sort DESC')
    ret = [(str(r.id), r.name) for r in sets]
    if insert_empty:
        # 在第一项插入一个空项
        ret.insert(0, ('', ''))

    return ret

def get_partner(id):
    """
    获取给定的合作商家信息
    """
    sets = db.select('partner', where = 'id = $id', vars = locals())
    if sets:
        return sets[0]
    return False

def update_partner(id, name, domain, spread_url, logo, sort):
    """
    更新合作商家
    """
    sql = '''UPDATE partner SET name = $name, 
                            domain = $domain,
                            spread_url = $spread_url,
                            sort = $sort'''
    if logo > 0:
        sql += ',logo = $logo'
    sql += ' WHERE id = $id;'
    return db.query(sql, vars = locals())

def add_partner(name, domain, spread_url, logo, sort):
    """
    添加合作商家
    """
    sql = '''INSERT INTO partner SET name = $name, 
                            domain = $domain,
                            spread_url = $spread_url,
                            sort = $sort'''
    if logo > 0:
        sql += ',logo = $logo'
    return db.query(sql, vars = locals())

def partner_search(word, pindex, perpage):
    """
    检索合作方信息
    @word as string, 关键词，匹配合作方的名字
    @pindex as int, 页码
    @perpage as int, 每页记录数

    returns:
        storage(result, totals)
    """
    where = ''
    if word:
        where = " WHERE name LIKE '%" + word + "%'"

    return get_all_partners(pindex * perpage, perpage, where)

def get_all_partners(offset, length, where = ''):
    """
    获取所有合作方记录
    """
    sets = db.query('''
            SELECT SQL_CALC_FOUND_ROWS * 
            FROM partner 
            %s
            ORDER BY sort DESC 
            LIMIT $offset, $length;''' % where
            , vars = locals())
    # 获取记录总数
    totals = db.query('SELECT FOUND_ROWS() AS totals;')
    # 返回组合结果
    return storage(result = sets
            , totals = int(totals[0].totals))
